import React, { useState, useEffect } from 'react';

import "./select.less"

import { Select, Input } from 'antd';

const { Option } = Select;

import { nanoid } from 'nanoid'
export default function(props){
  let a = []
  if(!Array.isArray(props.arr)) return
  props.arr.forEach(i => {
    a.push({name: i.name, show: false,M:i.M, N: i.N, key: nanoid()})
  })
  const [newArr, setNewArr] = useState(a)
  // const [select, setSelect] = useState([])  // 选中的
  const children = [];
  for (let i = 0; i < newArr.length; i++) {
    children.push(<Option key={newArr[i].key}>{newArr[i].name}</Option>);
  }

  const handleChange = (value) => {  //  选中的 select
    let a = JSON.parse(JSON.stringify(newArr))
    let b = a.map(m => ({...m, show: value.indexOf(m.key) > -1? true : false }))
    setNewArr(b)
    props.onChange(b)
  }
  const handleInput = (e, key, index) => {  // 修改 M 的input 数据
    let value = e.target.value
    let a = JSON.parse(JSON.stringify(newArr))
    let b = a.filter(m => {
      return m.key === key
    })[0]
    if(value.length > 0) {
      b.M = value
    } else if(value.length === 0) {
      b.M = ' '
    }
    a.splice(index, 1, b)
    setNewArr(a)
    props.onChange(a)
  }

  const handleInput_N = (e, key, index) => {
    let value = e.target.value
    let a = JSON.parse(JSON.stringify(newArr))
    let b = a.filter(m => {
      return m.key === key
    })[0]
    
    if(value) {
      b.N = value
    }else if(value.length === 0) {
      b.N = ' '
    }
    a.splice(index, 1, b)
    setNewArr(a)
    props.onChange(a)
  }

  return (
    <div style={{padding: '20px'}} >
        <Select
          mode="multiple"
          style={{ width: '100%' }}
          placeholder="请输入"
          onChange={handleChange}
          
        >
          {children}
        </Select>

        { newArr.length>0 && newArr.map((item, index) => {
          return (
            <div
              key={item.key}
            > 
              { item.show ? (
                <div  style={{
                  marginTop: '15px',
                  background: '#f4f5f6',
                  padding: '8px'
                }} >
                  <div> {item.name}  </div>
                  { item.M &&  ( 
                  <div style={{display: 'flex', marginTop: '15px'}} > 
                    <div>M =</div> <Input style={{width: '100px'}} onChange={(e) => handleInput(e, item.key, index)} /> 
                  </div> ) }
                  { item.N &&  (
                  <div style={{display: 'flex', marginTop: '15px'}}  > 
                    <div>N =</div> <Input style={{width: '100px'}} onChange={(e) => handleInput_N(e, item.key, index)} /> 
                  </div>) }
                </div> 
              ) : null}
            </div>
          )
        }) }
    </div>
  )
}